<?php
/************************************************************************************************
*   This file is a part of JV-LinkExchanger, a link exchange component for Joomla
*   Copyright (C) 2007-2008  Vijaykumar Niranjan 
*	
*   This program is free software; you can redistribute it and/or modify 
*   it under the terms of the GNU General Public License as published by 
*   the Free Software Foundation; either version 2 of the License, or 
*  (at your option) any later version. 
*
*   This program is distributed in the hope that it will be useful, 
*   but WITHOUT ANY WARRANTY; without even the implied warranty of 
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
*   GNU General Public License for more details. 
*
*   You should have received a copy of the GNU General Public License 
*   along with this program; if not, write to the Free Software 
*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
* 	JV-LinkExchanger - Link Exchange Component for Joomla 1.0.x
* 	@package JV-LinkExchanger
* 	@file version 1.3.0 RELEASE
* 	@author Vijaykumar Niranjan
* 	@link http://www.jv-extensions.com
* 	@copyright (C) 2007-2009 by Vijaykumar Niranjan
* 	@license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*  	This program is distributed with the hope that it will be useful,
*  	but WITHOUT ANY WARRANTY; without even the implied warranty of
*  	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
***************************************************************************************************/
// PHP Script that is scheduled to run for automatic reciprocal link checks
define('_VALID_MOS', 1);
require_once('../../configuration.php');

/* v1.2.6: Change done for Joomla 1.5.x legacy mode compatibility for accessing configuration.php directly */
if (class_exists('JConfig'))
{
	$cfg = new JConfig;	
	$M_host = $cfg->host;
	$M_user = $cfg->user;
	$M_pwd = $cfg->password;
	$M_dbase = $cfg->db;
	$M_prefix = $cfg->dbprefix;			
}
else
{
	$M_host = $mosConfig_host;
	$M_user = $mosConfig_user;
	$M_pwd = $mosConfig_password;
	$M_dbase = $mosConfig_db;
	$M_prefix = $GLOBALS['mosConfig_dbprefix'];
}
$M_abspath = dirname(__FILE__);

function get_category_name($dblnk, $id)
{
	global $M_dbase, $M_host, $M_prefix, $M_pwd, $M_user;
	
	$sql = "select name from #__jvlinx_categories where id = '".$id."'";
	$result = mysql_query(str_replace('#__',$M_prefix,$sql), $dblnk);
	if ($res = mysql_fetch_array($result))
		return $res['name'];
}

function get_site_url($dblnk)
{
	global $M_dbase, $M_host, $M_prefix, $M_pwd, $M_user;
	
	$sql = "select site_url from #__jvlinx_settings";
	$result = mysql_query(str_replace('#__',$M_prefix,$sql), $dblnk);
	if ($res = mysql_fetch_array($result))
		return $res['site_url'];
}

function get_site_email($dblnk)
{
	global $M_dbase, $M_host, $M_prefix, $M_pwd, $M_user;
	
	$sql = "select site_email from #__jvlinx_settings";
	$result = mysql_query(str_replace('#__',$M_prefix,$sql), $dblnk);
	if ($res = mysql_fetch_array($result))
		return $res['site_email'];
}

function get_result_mode($dblnk)
{
	global $M_dbase, $M_host, $M_prefix, $M_pwd, $M_user;
	
	$sql = "select result_mode from #__jvlinx_settings";
	$result = mysql_query(str_replace('#__',$M_prefix,$sql), $dblnk);
	if ($res = mysql_fetch_array($result))
		return $res['result_mode'];
}

function get_site_run($dblnk)
{
	global $M_dbase, $M_host, $M_prefix, $M_pwd, $M_user;
	
	$sql = "select enable_scheduler from #__jvlinx_settings";
	$result = mysql_query(str_replace('#__',$M_prefix,$sql), $dblnk);
	if ($res = mysql_fetch_array($result))
		return $res['enable_scheduler'];
}

function checkReciprocalLink($siteurl, $recip, &$error)
{
	global $M_dbase, $M_host, $M_prefix, $M_pwd, $M_user;
	
	$error = "";
	$recip=explode("?",$recip);
	$recip=$recip[0];
	$recip=trim($recip,"/");

	// Do exact match so that, partner does not point to invalid URLs by tweaking
	$urls_to_be_checked = array();
	array_push($urls_to_be_checked, "href='".$recip."'");
	array_push($urls_to_be_checked, 'href="'.$recip.'"');

    /* Added for accomodating slash for the link, during reciprocal link check */
    array_push($urls_to_be_checked, "href='".$recip."/'");
    array_push($urls_to_be_checked, 'href="'.$recip.'/"');            
	
	preg_match("/^(http:\/\/)?([^\/]+)/i",$siteurl, $hostname); //get the hostname        
	$host = $hostname[2];
	$tail = str_replace($hostname[0], "", $siteurl);  
	for($x=0;$x<2;$x++) 
	{
		$startfile = @fsockopen($host, '80'); //open my page socket            
		if ($startfile) 
		{	
			if(trim($tail)=="")
			{                    
				$page = "/";
			}
			else
			{
				$page = $tail;
			}
			fputs($startfile, "GET ".$page." HTTP/1.0\r\nHost: ".$host."\r\n\r\n");
			while(!feof($startfile)) 
			{
				$indexfile .= fgets($startfile, 10240);
			}
			for ($i=0; $i<count($indexfile); $i++)
			{
				$text = $text . $indexfile[$i];
			}
			/* Search the URLs now in partner page */
			for ($url_in=0,$k=0;$k<count($urls_to_be_checked);$k++)
			{
				$check_url = $urls_to_be_checked[$k];
				if (eregi($check_url, $indexfile))
				{
					$url_in = 1;
					break;
				}
			}
			if ($url_in)
			{
				return true; // set true if there is a backlink
			}
			else
			{
				return false; // set false if backlink is missing					
			}
			fclose($startfile);
		}
		else
		{
			$error = "Read Error";
			return false;
		}
	}
	return $output;	
}

$start_time = date("M j Y H:i:s", time());
// Get the list of all two way links from the link directory which are enabled for automatic link checking
$dblnk = mysql_connect($M_host, $M_user, $M_pwd) or die(mysql_error());
mysql_select_db($M_dbase, $dblnk);

$continue_run = get_site_run($dblnk);
if ($continue_run == "no")
	exit();	
// Get my website URL
$siteurl = get_site_url($dblnk);
$siteemail = get_site_email($dblnk);
$rmode = get_result_mode($dblnk);
// Get link information to query
$out_id = $out_url = $out_title = $out_email = $out_recipurl = $out_category = $out_cstatus = array();
$sql = "select * from #__jvlinx_links where link_type = 'TWO-WAY' and enable_scheduler = 'yes'";
$result = mysql_query(str_replace('#__',$M_prefix,$sql), $dblnk);
while ($res = mysql_fetch_array($result))
{
	array_push($out_id, $res['id']);
	array_push($out_url, $res['partner_url']);
	array_push($out_title, $res['partner_title']);
	array_push($out_email, $res['partner_email']);
	array_push($out_recipurl, $res['reciprocal_link_url']);
	array_push($out_category, get_category_name($dblnk, $res['link_category']));	
	array_push($out_cstatus, $res['link_status']);
}
// check reciprocal link status
$out_result = $out_remarks = $out_nstatus = array();
for ($i=0;$i<count($out_url);$i++)
{
	$error = "";
	if ($out_recipurl[$i] == "")
	{
		$error = "Empty Reciprocal link found for this link in your link directory.";
		$out_result[$i] = "Unknown";		
		$out_remarks[$i] = $error;			
		$out_action[$i] = " Please edit the link with reciprocal link info. May be you have initiated this link exchange. You may contact the partner for the location of reciprocal link";			
		$out_nstatus[$i] = "UNKNOWN";					
	}	
	else
	{
		$ret = checkReciprocalLink($out_recipurl[$i], $siteurl, $error);
		if ($ret == true) // established
		{
			$out_result[$i] = "Passed";
			$out_remarks[$i] = "Reciprocal link back to your website is intact";
			$out_action[$i] = "-";
			$out_nstatus[$i] = "ESTABLISHED";
		}
		else
		{
			if ($error != "")	// Some error has occured during check, unknown
			{
				$out_result[$i] = "Unknown";		
				$out_remarks[$i] = $error;			
				$out_action[$i] = "If the link is pending, you may remind your partner. If already in place, then please check the reciprocal link manually";			
				$out_nstatus[$i] = "UNKNOWN";			
			}	
			else	// Backlink is unavailable at partner website // pending
			{
				$out_result[$i] = "Failed";
				$out_remarks[$i] = "Reciprocal link back to your website does not exist at partner URL";
				$out_action[$i] = "The reciprocal link to your website may have been moved or deleted at partner side. Please consult the partner immediately";			
				$out_nstatus[$i] = "PENDING";			
			}
		}
	}	
	
	$sql = "update #__jvlinx_links set rlc_last_checked_on = '".time()."', link_status = '".$out_nstatus[$i]."' where id = '".$out_id[$i]."'";
	mysql_query(str_replace('#__',$M_prefix,$sql), $dblnk);
	
	sleep(1);
}
$end_time = date("M j Y H:i:s", time());

$html_msg = "<html><head></head><body>";
$html_msg .= "<center>***************************************************************************************<br>";
$html_msg .= "<strong>JV-LinkExchanger</strong>: Results of scheduled automatic reciprocal link checks for all two way links which have the scheduled check parameter enabled are as follows. Reciprocal link checks Start time ".$start_time; 
$html_msg .= "<table width='100%' cellpadding='3' cellspacing='3' border='1'><tr>";
$html_msg .= "<th width='5%' align='center'>Sno</th>";
$html_msg .= "<th width='15%' align='center'>Partner URL</th>";
$html_msg .= "<th width='10%' align='center'>Check Result</th>";
$html_msg .= "<th width='25%' align='center'>Check Remarks</th>";
$html_msg .= "<th width='20%' align='center'>Suggested Action</th>";
$html_msg .= "<th width='15%' align='center'>Partner Email</th>";
$html_msg .= "<th width='5%' align='center'>Link Status Before Check</th>";
$html_msg .= "<th width='5%' align='center'>Link Status After Check</th>";
$html_msg .= "</tr>";
for ($j=1,$i=0;$i<count($out_url);$i++,$j++)
{
	$html_msg .= "<tr><td align='center'>$j</td>";
	$html_msg .= "<td align='center'>".$out_url[$i]."</td>";
	$html_msg .= "<td align='center'>".$out_result[$i]."</td>";
	$html_msg .= "<td align='center'>".$out_remarks[$i]."</td>";
	$html_msg .= "<td align='center'>".$out_action[$i]."</td>";
	$html_msg .= "<td align='center'>".$out_email[$i]."</td>";
	$html_msg .= "<td align='center'>".$out_cstatus[$i]."</td>";
	$html_msg .= "<td align='center'>".$out_nstatus[$i]."</td>";		
	$html_msg .= "</tr>";
}	
$html_msg .= "</table>";
$html_msg .= "***************************************************************************************<br>";
$html_msg .= "Reciprocal link checks Finish time ".$end_time."</center></body></html>";

// write to file/email
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: $siteemail";
	
if ($rmode == "email") 
	mail($siteemail, "JV-LinkExchanger: Scheduled Automatic Reciprocal Links Check Results", $html_msg, $headers);
else
{
	$cdate = date("Y-m-d-H-i", time());
	$filename = $M_abspath."/temp/SRC_".$cdate.".html";
	$fp = fopen($filename, "w");
	if (!$fp)
		mail($siteemail, "JV-LinkExchanger: Scheduled Automatic Reciprocal Links Check Results", $html_msg, $headers);	
	else
	{
		fwrite($fp, $html_msg);
		fclose($fp);
		mail($siteemail, "JV-LinkExchanger: Scheduled Automatic Reciprocal Links Check Results", "Scheduled automatic reciprocal links check process is completed. The results have been consolidated into a file and stored in $filename You may FTP this file and view the results", $headers);	
	}	
}	
?>